using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace IntegratedMeasuring.Storage;

/// <summary>
/// 基础存储操作类
/// 提供通用的数据库增删改查操作
/// </summary>
public abstract class BaseStorage
{
    protected readonly object _writeLock = new object();
    protected readonly SqlSugarScope _db;

    public abstract void InitRuntimeTables();
    
    protected BaseStorage(string connectionString)
    {
        _db = new SqlSugarScope(new ConnectionConfig()
        {
            ConnectionString = connectionString,
            DbType = DbType.Sqlite,
            IsAutoCloseConnection = true,
            InitKeyType = InitKeyType.Attribute
        });
    }

    /// <summary>
    /// 插入单个实体
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="entity">实体对象</param>
    /// <returns>是否成功</returns>
    public bool Insert<T>(T entity) where T : class, new()
    {
        lock (_writeLock)
        {
            try
            {
                return _db.Insertable(entity).ExecuteCommand() > 0;
            }
            catch (Exception ex)
            {
                // TODO: 记录日志
                return false;
            }
        }
    }

    /// <summary>
    /// 异步插入单个实体
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="entity">实体对象</param>
    /// <returns>是否成功</returns>
    public async Task<bool> InsertAsync<T>(T entity) where T : class, new()
    {
        return await Task.Run(() => Insert(entity));
    }
    
    /// <summary>
    /// 批量插入实体
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="entities">实体列表</param>
    /// <returns>是否成功</returns>
    public bool InsertRange<T>(List<T> entities) where T : class, new()
    {
        lock (_writeLock)
        {
            try
            {
                return _db.Insertable(entities).ExecuteCommand() > 0;
            }
            catch (Exception ex)
            {
                // TODO: 记录日志
                return false;
            }
        }
    }

    /// <summary>
    /// 异步批量插入实体
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="entities">实体列表</param>
    /// <returns>是否成功</returns>
    public async Task<bool> InsertRangeAsync<T>(List<T> entities) where T : class, new()
    {
        return await Task.Run(() => InsertRange(entities));
    }

    /// <summary>
    /// 更新实体
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="entity">实体对象</param>
    /// <returns>是否成功</returns>
    public bool Update<T>(T entity) where T : class, new()
    {
        lock (_writeLock)
        {
            try
            {
                return _db.Updateable(entity).ExecuteCommand() > 0;
            }
            catch (Exception ex)
            {
                // TODO: 记录日志
                return false;
            }
        }
    }

    /// <summary>
    /// 异步更新实体
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="entity">实体对象</param>
    /// <returns>是否成功</returns>
    public async Task<bool> UpdateAsync<T>(T entity) where T : class, new()
    {
        return await Task.Run(() => Update(entity));
    }

    /// <summary>
    /// 删除实体
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="entity">实体对象</param>
    /// <returns>是否成功</returns>
    public bool Delete<T>(T entity) where T : class, new()
    {
        lock (_writeLock)
        {
            try
            {
                return _db.Deleteable(entity).ExecuteCommand() > 0;
            }
            catch (Exception ex)
            {
                // TODO: 记录日志
                return false;
            }
        }
    }

    /// <summary>
    /// 异步删除实体
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="entity">实体对象</param>
    /// <returns>是否成功</returns>
    public async Task<bool> DeleteAsync<T>(T entity) where T : class, new()
    {
        return await Task.Run(() => Delete(entity));
    }

    /// <summary>
    /// 根据条件删除
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="expression">删除条件</param>
    /// <returns>是否成功</returns>
    public bool Delete<T>(System.Linq.Expressions.Expression<Func<T, bool>> expression) where T : class, new()
    {
        lock (_writeLock)
        {
            try
            {
                return _db.Deleteable<T>().Where(expression).ExecuteCommand() > 0;
            }
            catch (Exception ex)
            {
                // TODO: 记录日志
                return false;
            }
        }
    }

    /// <summary>
    /// 异步根据条件删除
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="expression">删除条件</param>
    /// <returns>是否成功</returns>
    public async Task<bool> DeleteAsync<T>(System.Linq.Expressions.Expression<Func<T, bool>> expression) where T : class, new()
    {
        return await Task.Run(() => Delete(expression));
    }

    /// <summary>
    /// 查询所有数据
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <returns>数据列表</returns>
    public List<T> QueryAll<T>() where T : class, new()
    {
        try
        {
            return _db.Queryable<T>().ToList();
        }
        catch (Exception ex)
        {
            // TODO: 记录日志
            return new List<T>();
        }
    }

    /// <summary>
    /// 异步查询所有数据
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <returns>数据列表</returns>
    public async Task<List<T>> QueryAllAsync<T>() where T : class, new()
    {
        return await Task.Run(() => QueryAll<T>());
    }

    /// <summary>
    /// 根据条件查询
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="expression">查询条件</param>
    /// <returns>数据列表</returns>
    public List<T> Query<T>(System.Linq.Expressions.Expression<Func<T, bool>> expression) where T : class, new()
    {
        try
        {
            return _db.Queryable<T>().Where(expression).ToList();
        }
        catch (Exception ex)
        {
            // TODO: 记录日志
            return new List<T>();
        }
    }

    /// <summary>
    /// 查询第一个符合条件的实体（降序）
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="expression">查询条件</param>
    /// <param name="orderBy">排序字段</param>
    /// <returns>实体对象</returns>
    public T QueryFirstDesc<T>(System.Linq.Expressions.Expression<Func<T, bool>> expression, string orderBy) where T : class, new()
    {
        try
        {
            var query = _db.Queryable<T>().Where(expression);
            if (!string.IsNullOrWhiteSpace(orderBy))
            {
                query = query.OrderBy($"{orderBy} desc");
            }
            return query.First();
        }
        catch (Exception)
        {
            // TODO: 记录日志
            return null;
        }
    }

    /// <summary>
    /// 异步根据条件查询
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="expression">查询条件</param>
    /// <returns>数据列表</returns>
    public async Task<List<T>> QueryAsync<T>(System.Linq.Expressions.Expression<Func<T, bool>> expression) where T : class, new()
    {
        return await Task.Run(() => Query(expression));
    }

    /// <summary>
    /// 根据ID查询单个实体
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="id">主键ID</param>
    /// <returns>实体对象</returns>
    public T QueryById<T>(object id) where T : class, new()
    {
        try
        {
            return _db.Queryable<T>().InSingle(id);
        }
        catch (Exception ex)
        {
            // TODO: 记录日志
            return null;
        }
    }

    /// <summary>
    /// 异步根据ID查询单个实体
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="id">主键ID</param>
    /// <returns>实体对象</returns>
    public async Task<T> QueryByIdAsync<T>(object id) where T : class, new()
    {
        return await Task.Run(() => QueryById<T>(id));
    }

    /// <summary>
    /// 分页查询
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="pageIndex">页码</param>
    /// <param name="pageSize">页大小</param>
    /// <param name="expression">查询条件</param>
    /// <returns>分页结果</returns>
    public (List<T> Data, int Total) QueryPage<T>(int pageIndex, int pageSize, System.Linq.Expressions.Expression<Func<T, bool>> expression = null) where T : class, new()
    {
        try
        {
            var query = _db.Queryable<T>();
            if (expression != null)
            {
                query = query.Where(expression);
            }

            var total = query.Count();
            var data = query.ToPageList(pageIndex, pageSize);
            return (data, total);
        }
        catch (Exception ex)
        {
            // TODO: 记录日志
            return (new List<T>(), 0);
        }
    }

    /// <summary>
    /// 异步分页查询
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="pageIndex">页码</param>
    /// <param name="pageSize">页大小</param>
    /// <param name="expression">查询条件</param>
    /// <returns>分页结果</returns>
    public async Task<(List<T> Data, int Total)> QueryPageAsync<T>(int pageIndex, int pageSize, System.Linq.Expressions.Expression<Func<T, bool>> expression = null) where T : class, new()
    {
        return await Task.Run(() => QueryPage(pageIndex, pageSize, expression));
    }

    /// <summary>
    /// 创建数据库表
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    public void CreateTable<T>() where T : class, new()
    {
        lock (_writeLock)
        {
            try
            {
                _db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(T));
            }
            catch (Exception ex)
            {
                // TODO: 记录日志
            }
        }
    }

    /// <summary>
    /// 异步创建数据库表
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    public async Task CreateTableAsync<T>() where T : class, new()
    {
        await Task.Run(() => CreateTable<T>());
    }
} 